<template>
  <div class="tag-management-page">
    <div class="page-header">
      <h2>标签管理</h2>
      <el-divider />
    </div>
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form inline :model="queryParams" ref="queryFormRef">
        <el-form-item label="关键字">
          <el-input
              placeholder="请输入标签名称"
              v-model="queryParams.keywords"
              clearable
              @keyup.enter="handleQuery"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select
              v-model="queryParams.categoryId"
              placeholder="请选择分类"
              clearable
          >
            <el-option
                v-for="category in categoryList"
                :key="category.categoryId"
                :label="category.name"
                :value="category.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              :icon="Search"
              @click="handleQuery"
          >
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
              :icon="Refresh"
              @click="resetQuery"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button
          type="success"
          :icon="Plus"
          @click="openAddDialog"
      >
        标签新增
      </el-button>
    </div>
    <!-- 标签列表 -->
    <el-card class="content-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">标签列表</span>
          <el-badge :value="tagList.length" type="primary" />
        </div>
      </template>
      <el-table
          :data="tagList"
          v-loading="loading"
          border
          highlight-current-row
          :row-class-name="tableRowClassName"
      >
        <el-table-column prop="tagId" label="编号" width="70px" align="center" />
        <el-table-column prop="tagName" label="名称" />
        <el-table-column prop="categoryId" label="分类">
          <template #default="scope">
            <el-tag size="small">{{ getCategoryName(scope.row.categoryId) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="简介" />
        <el-table-column label="操作" width="200px" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                  type="text"
                  size="small"
                  :icon="EditPen"
                  @click="handleModify(scope.row)"
                  class="edit-btn"
              >
                修改
              </el-button>
              <el-button
                  type="text"
                  size="small"
                  :icon="Delete"
                  @click="handleDelete(scope.row.tagId)"
                  class="delete-btn"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="queryParams.pageNum"
          :page-sizes="[8, 16, 32, 64]"
          v-model:page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <!-- 标签编辑对话框 -->
    <el-dialog
        :title="isAdd ? '新增标签' : '修改标签'"
        v-model="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
        @close="handleDialogClose"
    >
      <el-form
          :model="currentTag"
          ref="tagFormRef"
          :rules="rules"
          label-width="80px"
          size="default"
      >
        <el-form-item label="标签名" prop="tagName">
          <el-input
              v-model="currentTag.tagName"
              placeholder="请输入标签名称"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select
              v-model="currentTag.categoryId"
              placeholder="请选择分类"
              clearable
          >
            <el-option
                v-for="category in categoryList"
                :key="category.categoryId"
                :label="category.name"
                :value="category.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
              type="textarea"
              v-model="currentTag.description"
              placeholder="请输入标签描述"
              :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitTagForm">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { Search, Refresh, Delete, EditPen, Plus } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { SocPostTags } from '@/api/social/post/type';
import {
  reqAddPostTag,
  reqDeletePostTagById,
  reqGetPostTagPage,
  reqGetPostCategoryList,
  reqUpdatePostTag,
  reqGetPostTagById
} from '@/api/social/post';

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 8,
  keywords: "",
  categoryId: ""
});

// 状态管理
const loading = ref<boolean>(true);
const tagList = ref<SocPostTags[]>([]);
const categoryList = ref([]);
const total = ref<number>(0);
const dialogVisible = ref(false);
const isAdd = ref(true);
const tagFormRef = ref<FormInstance>();
const queryFormRef = ref<FormInstance>();

// 当前操作的标签
const currentTag = ref<SocPostTags>({
  tagId: undefined,
  tagName: "",
  categoryId: null,
  description: ""
});

// 表单验证规则
const rules = reactive<FormRules<SocPostTags>>({
  tagName: [
    { required: true, message: "请输入标签名称", trigger: "blur" },
    { min: 2, max: 20, message: "标签名称长度在 2 到 20 个字符", trigger: "blur" }
  ],
  categoryId: [
    { required: true, message: "请选择分类", trigger: "change" }
  ]
});

// 获取标签列表
const getTagList = () => {
  loading.value = true;
  reqGetPostTagPage(queryParams).then((res) => {
    tagList.value = res.data.list || [];
    total.value = res.data.total || 0;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

// 获取分类列表
const getCategoryList = () => {
  reqGetPostCategoryList().then(res => {
    categoryList.value = res.data || [];
  });
};

// 根据分类ID获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categoryList.value.find((item: any) => item.categoryId === categoryId);
  return category ? category.name : '未知分类';
};

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  getTagList();
};

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  queryParams.categoryId = "";
  getTagList();
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getTagList();
};

// 处理页码变化
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  getTagList();
};

// 打开新增对话框
const openAddDialog = () => {
  isAdd.value = true;
  currentTag.value = {
    tagId: undefined,
    tagName: "",
    categoryId: null,
    description: ""
  };
  dialogVisible.value = true;
};

// 处理修改
const handleModify = (row: SocPostTags) => {
  reqGetPostTagById(row.tagId).then((res) => {
    currentTag.value = { ...res.data };
    isAdd.value = false;
    dialogVisible.value = true;
  });
};

// 处理删除
const handleDelete = (tagId: string) => {
  ElMessageBox.confirm(
      "确定要删除这个标签吗？删除后不可恢复。",
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }
  ).then(() => {
    reqDeletePostTagById(tagId).then(() => {
      ElMessage.success("删除成功");
      getTagList();
    });
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
};

// 提交表单
const submitTagForm = async () => {
  if (!tagFormRef.value) return;

  try {
    await tagFormRef.value.validate();

    if (isAdd.value) {
      await reqAddPostTag(currentTag.value);
      ElMessage.success("新增标签成功");
    } else {
      await reqUpdatePostTag(currentTag.value);
      ElMessage.success("修改标签成功");
    }

    dialogVisible.value = false;
    getTagList();
  } catch (error) {
    // 表单验证失败
    return;
  }
};

// 处理对话框关闭
const handleDialogClose = () => {
  tagFormRef.value?.resetFields();
};

// 表格行样式
const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
};

// 初始化
onMounted(() => {
  getTagList();
  getCategoryList();
});

// 监听查询参数变化
watch([() => queryParams.pageNum, () => queryParams.pageSize], () => {
  getTagList();
});
</script>

<style scoped>
.tag-management-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #1f2329;
  margin-bottom: 10px;
}

.search-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.action-buttons {
  margin-bottom: 20px;
}

.content-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.content-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: 600;
  font-size: 16px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.edit-btn {
  color: #409eff;
}

.edit-btn:hover {
  color: #66b1ff;
  background-color: #ecf5ff;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f78989;
  background-color: #fef0f0;
}

.even-row {
  background-color: #f9fafb;
}

.odd-row {
  background-color: #ffffff;
}

::v-deep .el-table__row:hover > td {
  background-color: #f0f7ff !important;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
